package cn.javabb.web.controller.biz;

import cn.javabb.common.exception.ForbiddenException;
import cn.javabb.common.exception.ParameterException;
import cn.javabb.common.model.ResponseModel;
import cn.javabb.common.utils.PageUtil;
import cn.javabb.common.utils.ResultUtil;
import cn.javabb.core.base.BaseController;
import cn.javabb.core.bo.PostBO;
import cn.javabb.core.constant.BizConstant;
import cn.javabb.core.constant.SysConstant;
import cn.javabb.core.entity.biz.CatalogDO;
import cn.javabb.core.entity.biz.CommentDO;
import cn.javabb.core.entity.biz.NavDO;
import cn.javabb.core.entity.biz.PostDO;
import cn.javabb.core.entity.sys.UserDO;
import cn.javabb.core.query.PostQuery;
import cn.javabb.core.service.biz.*;
import cn.javabb.core.service.sys.SysConfigService;
import cn.javabb.core.service.sys.UserService;
import cn.javabb.core.util.ShiroUtil;
import cn.javabb.core.vo.PostVO;
import cn.javabb.log.action.DeleteAction;
import cn.javabb.log.annotation.Log;
import com.github.pagehelper.Page;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;
import java.util.Map;

/**
 * @Author QINB imqinbao@163.com
 * @CreateDate 2019/1/9/009 0:14
 * @Since V1.0
 */
@Controller
@RequestMapping("/post")
public class PostController extends BaseController {

    @Autowired
    CatalogTypeService catalogTypeService;
    @Autowired
    PostService postService;
    @Autowired
    CommentService commentService;
    @Autowired
    PostHideService postHideService;
    @Autowired
    UserService userService;
    @Autowired
    private CatalogService catalogService;
    @Autowired
    private NavService navService;
    @Autowired
    private SysConfigService configService;

    @GetMapping("/publish")
    public String publish(Integer catalogId, Model model){
        model.addAttribute("catalogId",catalogId);
        model.addAttribute("catalogTypeList",catalogTypeService.listByCatalogId(catalogId));
        return "web/view/bbs/postPublish";
    }


    /**
     * 	发布文章
     * @param postVO
     * @return
     */
    @RequiresAuthentication
    @ResponseBody
    @PostMapping("/publish")
    public Object doPublish(PostVO postVO){
        if(StringUtils.isBlank(postVO.getPostTitle())) {
        	return ResponseModel.Failure("保存失败，标题不能为空");
        }
        if (null == postVO.getCatalogId()) {
            return ResponseModel.Failure("版块选择不能为空");
        }
        postVO.setUserId(getLoginUser().getId());
        if(StringUtils.isBlank(postVO.getContent())) {
        	return ResponseModel.Failure("保存失败，内容不能为空");
        }
        if(postService.savePost(postVO)) {
        	return ResponseModel.Success("发布成功");
        }
        return ResponseModel.Failure("发布失败");
    }
    /**
     * 按照类别分页查询帖子
     * @param catalogId
     * @param query
     * @param model
     * @return
     */
    @GetMapping("/{catalogId}/{page}")
    public String catalogDetial(@PathVariable Integer catalogId,@PathVariable Integer page, PostQuery query,
                                Model model){

        CatalogDO catalog = catalogService.getCatalogById(catalogId);
        model.addAttribute("catalog",catalog);
        //获取全局置顶的帖子
        List<PostDO> listTopArticles = postService.listTopPosts(BizConstant.POST_TOP_GLOBAL,4);
        query.setCatalogId(catalogId);
        query.setPage(page);
        Page articlePage = postService.queryPageByCatalogId(query);
        // side 展示
        Integer sideShowSize = Integer.parseInt(configService.getConfigValue(BizConstant.CONFIG_POST_SIDE_SHOW_TOTAL,"8"));
        Map<String,List<PostDO>> mapListPosts = postService.mapListPosts(sideShowSize);

        String pagination = PageUtil.genPagination("/post/"+catalogId+"/",articlePage.getTotal(),query.getPage(),query.getSize());

        List<UserDO> rankUsers = userService.rankUserComment();

        List<NavDO> quickNavs = navService.listNavs(4);

        model.addAttribute("rankUsers",rankUsers);
        model.addAttribute("mapListPosts",mapListPosts);
        model.addAttribute("listTopArticles",listTopArticles);
        model.addAttribute("quickNavs",quickNavs);
        model.addAttribute("listArticles",articlePage.getResult());
        model.addAttribute("pagination", pagination);
        return "web/view/bbs/catalogDetail";
    }
    @GetMapping("/{id}")
    public ModelAndView postDetail(@PathVariable Integer id, Model model){
        UserDO loginUser = getLoginUser();
        //有评论数据
        PostBO postDetail = postService.getPostDetail(id,loginUser==null?null:loginUser.getId());
        if(null == postDetail){
            return ResultUtil.error(404);
        }
        List<PostDO> recommenedPosts = postService.listHotPosts(5);
        postService.postClick(id);
        Map<String,List<PostDO>> mapListPosts = postService.mapListPosts(8);
        model.addAttribute("mapListPosts",mapListPosts);
        model.addAttribute("postDetail",postDetail);
        model.addAttribute("recommenedPosts",recommenedPosts);
        return ResultUtil.view("web/view/bbs/postDetail");
    }
    @RequiresAuthentication
    @PostMapping("/comment")
    @ResponseBody
    public Object comment(CommentDO comment){
        if(StringUtils.isBlank(comment.getCommentContent())){
            return ResponseModel.Failure("评论内容不能为空");
        }
        if(comment.getArticleId()==null){
            return ResponseModel.Failure("参数错误",403);
        }
        if (!postService.checkCommentAble(comment.getArticleId())) {
            return ResponseModel.Failure("帖子状态错误或者该帖子禁止评论");
        }
        UserDO loginUser = getLoginUser();
        comment.setUserId(loginUser.getId());
        comment.setArticleType(BizConstant.ARTICLE_TYPE_POST);
        comment.setCommentUsername(loginUser.getUserName());
        String result = commentService.saveComment(comment);
        if("insert".equals(result)){
            return ResponseModel.Success("评论成功");
        }else if("update".equals(result)){
            return ResponseModel.Success("修改成功");
        }

        return ResponseModel.Failure("评论失败");
    }

    /**
     * 购买资源
     *  1，先判断用户元宝数目大不大
     *
     * @param hideContentId
     * @param price
     * @return
     */
    @RequiresAuthentication
    @ResponseBody
    @PostMapping("/buyHideContent")
    public Object buyHideContent(@RequestParam Integer hideContentId,Integer price){
        UserDO loginUser = ShiroUtil.getLoginUser();
        if(postHideService.buyHideContentEnable(hideContentId,loginUser.getId())){
            if(postHideService.buyHideContent(hideContentId,loginUser.getId())){
                userService.refreshSessionUser(loginUser.getId(),request);
                return ResponseModel.Success("购买成功");
            }
        }else{
            return ResponseModel.Failure("当前元宝不够，请先充值");
        }
        return ResponseModel.Failure("购买失败");

    }

    @ResponseBody
    @RequiresRoles(SysConstant.ADMIN_ROLE_CODE)
    @PostMapping("/doTop")
    public Object doTop(Integer postId,Integer top) {
        if (postService.updateTop(postId,top)) {
            return ResponseModel.Success("保存成功");
        }
        return ResponseModel.Failure("保存失败");
    }
    @ResponseBody
    @RequiresRoles(SysConstant.ADMIN_ROLE_CODE)
    @PostMapping("/doSupport")
    public Object doSupport(Integer postId,Integer support) {
        if (postService.updateSupport(postId,support)) {
            return ResponseModel.Success("保存成功");
        }
        return ResponseModel.Failure("保存失败");
    }

    /**
     * 前台web删除
     * @param postId
     * @return
     */
    @ResponseBody
    @RequiresRoles(SysConstant.ADMIN_ROLE_CODE)
    @PostMapping("/doDelete")
    public Object doDelete(Integer postId) {
        if (postService.delete(String.valueOf(postId))) {
            return ResponseModel.Success("删除成功");
        }
        return ResponseModel.Failure("删除失败");
    }
    /**
     * 举报
     * @param postId
     * @return
     */
    @ResponseBody
    @RequiresAuthentication
    @PostMapping("/doReport")
    public Object doReport(Integer postId) {
        return ResponseModel.Failure("删除失败");
    }

    /**
     * 用户帖子
     * @return
     */
    @ResponseBody
    @RequiresAuthentication
    @GetMapping("/list")
    public Object postList(PostQuery query){
        query.setUserId(getLoginUser().getId());
        Page page = postService.listPostsPage(query);
        return ResponseModel.table(page);
    }
    /**
     * 删除
     * @return
     */
    @RequiresAuthentication
    @ResponseBody
    @PostMapping("/del")
    @Log(name = "帖子删除",action = DeleteAction.class)
    public Object delete(Integer id){
        if(null == id){
            throw new ParameterException();
        }
        if (!postService.judgeSameUser(id)) {
            throw new ForbiddenException();
        }
        if(postService.delete(String.valueOf(id))){
            return ResponseModel.Success("删除成功");
        }
        return ResponseModel.Failure("删除失败");
    }
}
